/*
 * @Descripttion: 
 * @version: 
 * @Author: 
 * @Date: 2022-05-05 15:08:11
 * @LastEditors: weidelong
 * @LastEditTime: 2022-05-05 17:16:14
 */
const express = require('express')
const usermsg = require('../db/mobileUserMsgSchema')// 聊天记录
const router = express.Router()

/* 后台端医师存储与用户的聊天记录 */
router.post('/saveUserMsg', async (req, res) => {
	const msg = req.body
    let haveMsg = await usermsg.find({})
    // 如果数据库没有数据
    if (haveMsg.length == 0) {
        usermsg.create(msg, (err, result) => {
            if (err) {
                throw error
            } else {
                res.send({
                    status: 200,
                    data: {
                        code: 0,
                    },
                    msg: '添加成功'
                })
            }
        })
    } else {
        usermsg.updateOne({}, msg, (err, docs) => {
            if (err) {
                throw err
            } else {
                res.send({
                    status: 200,
                    data: {
                        code: 0,
                    },
                    msg: '操作成功'
                })
            }
        })
    }
})

/* 后台端医师读取与用户的聊天记录 */
router.get('/searchUserMsg', async (req, res) => {
    let msgList = await usermsg.find({})
    if (msgList) {
        if (msgList.length == 0) {
            res.send({
                status: 200,
                data: {
                    code: 0,
                    msgList
                },
                msg: '查询成功'
            })
        } else {
            let msg1 = JSON.parse(msgList[0].msg)
            res.send({
                status: 200,
                data: {
                    code: 0,
                    msgList: msg1
                },
                msg: '查询成功'
            })
        }
    } else {
        res.send({
            status: 404,
            msg: '查询失败'
        })
    }
})

module.exports = router